package com.squirrel.serialportcore.utils;

import com.squirrel.serialportcore.exception.CoreException;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;

/**
 * 流工具
 *
 * @author Squbi
 * @date 2021/2/25 15:39
 */
public class StreamUtils {
    private StreamUtils() {
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的串口对象
     * @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) throws IOException {
        InputStream in = null;
        byte[] bytes = {};
        try {
            in = serialPort.getInputStream();
            // 缓冲区大小为一个字节
            byte[] readBuffer = new byte[1];
            int bytesNum = in.read(readBuffer);
            while (bytesNum > 0) {
                bytes = ByteUtils.concat(bytes, readBuffer);
                bytesNum = in.read(readBuffer);
            }
        } catch (IOException e) {
            throw new CoreException(e);
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return bytes;
    }
}
